package cn.tutu.blockchain.scheduled;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import cn.tutu.blockchain.cktrecord.entity.CktRecord;
import cn.tutu.blockchain.cktrecord.service.CktRecordService;
import cn.tutu.blockchain.cktuser.entity.CktUser;
import cn.tutu.blockchain.cktuser.service.CktUserService;
import cn.tutu.blockchain.common.TypeEnum;
import cn.tutu.blockchain.exchange.entity.Exchange;
import cn.tutu.blockchain.exchange.service.ExchangeService;
import cn.tutu.blockchain.fileInfo.service.FileInfoService;
import cn.tutu.blockchain.filebak.entity.Filebak;
import cn.tutu.blockchain.filebak.service.FilebakService;
import cn.tutu.blockchain.minemachine.entity.Minemachine;
import cn.tutu.blockchain.minemachine.service.MinemachineService;
import cn.tutu.blockchain.mining.service.MiningRecordsService;
import cn.tutu.blockchain.sysuser.entity.SysUser;
import cn.tutu.blockchain.sysuser.service.SysUserService;
import cn.tutu.blockchain.utils.HttpUtils;
import net.sf.json.JSONObject;

@Component
@Transactional
public class ScheduledTask {

	private static Logger LOGGER = LoggerFactory.getLogger(ScheduledTask.class);

	@Value("${cn.tutu.blockchain.transact.query}")
	private String url;

	@Autowired
	private MinemachineService machineService;

	@Autowired
	private FilebakService filebakService;

	@Autowired
	private FileInfoService fileInfoService;

	@Autowired
	private ExchangeService exchangeService;

	@Autowired
	private SysUserService sysUserService;

	@Autowired
	private MiningRecordsService miningRecordsService;

	@Autowired
	private CktRecordService cktRecordService;
	
	@Autowired
	private CktUserService cktUserService;

	/**
	 * 检测矿机是否失效，矿机最后更新时间超过一天判定为失效,每日0：50分执行
	 */
	@Scheduled(cron = "0 50 0 * * ?")
	public void checkMacStatus() {
		LOGGER.info("===============================>开始扫描失效矿机!!!!!!");
		// 获取当天没有更新的矿机信息，一次最多500台
		List<Minemachine> list = machineService.getByLastUpdateDate();
		// 失效矿机ID
		List<String> strList = new ArrayList<String>();
		try {
			if (null != list && list.size() > 0) {
				// 修改矿机状态，表示矿机已失效
				machineService.updateStatusBatch(list);
				// 根据矿机获取备份文件的信息
				for (Minemachine minemachine : list) {
					strList.add(minemachine.getMineMachineId());
					List<Filebak> bakList = filebakService.findByMacId(minemachine.getMineMachineId());
					if (bakList != null && bakList.size() > 0) {
						// 根据文件hash修改该文件的备份次数
						fileInfoService.updaeCountBatch(bakList);
						// 删除该矿机的备份记录
						filebakService.deleteByMacId(minemachine.getMineMachineId());
					}
				}
				LOGGER.info("===============================>失效矿机ID【{}】", strList.toString());

			}
		} catch (Exception e) {
			LOGGER.error("===============================>扫描失效矿机失败!!!!!!", e);
		}

	}

	/**
	 * 确认提现申请的转账记录是否成功 每次只确认一条申请记录,每10分钟执行一次
	 */
	@Scheduled(cron = "0 0/10 * * * ?")
	public void checkExchangeStatus() {
		LOGGER.info("===============================>开始确认转账提现状态!!!!!!");
		Exchange exchange = null;
		try {
			exchange = exchangeService.getOneByStatus(TypeEnum.STATUS_0.getCode());
			if (null == exchange) {
				return;
			}
			SysUser user = sysUserService.getById(exchange.getUserId());
			if (null == user) {
				LOGGER.info("交易号:{},的用户不存在!", exchange.getTransferNum());
				return;
			}
			Map<String, String> paraMap = new HashMap<String, String>();
			paraMap.put("hash", exchange.getTransferNum());
			Map<String, String> head = new HashMap<String, String>();
			head.put("content-type", "Content-Type:application/json;charset=UTF-8");
			head.put("channel", "APP");
			head.put("rt", user.getPhone());
			String para = JSONObject.fromObject(paraMap).toString();
			String responseBody = HttpUtils.postData(this.url, para, head);
			if (StringUtils.isEmpty(responseBody)) {
				LOGGER.info("交易号:{},调用接口发生错误", exchange.getTransferNum());
				exchangeService.modifyLastDate(exchange.getId());
				return;
			}
			JSONObject object = JSONObject.fromObject(responseBody);
			if (object.getString("code").equals("0")) {
				LOGGER.info("交易号:{},{}", exchange.getTransferNum(), "确认转账成功!");
				exchange.setStatus(TypeEnum.STATUS_2.getCode());
			} else {
				LOGGER.info("交易号:{},{}", exchange.getTransferNum(), "确认转账失败!");
				exchange.setStatus(TypeEnum.STATUS_1.getCode());
			}
			exchangeService.modifyStatus(exchange);
		} catch (Exception e) {
			LOGGER.error("{},确认提现申请处理失败!", exchange.getTransferNum(), e);
		}

	}

	/**
	 * 定时删除超过15天的挖矿记录，并将删除的数据接入备份表 每日0：30分执行
	 */
	@Scheduled(cron = "0 30 0 * * ?")
	public void delMiningRecord() {
		LOGGER.info("===============================>开始删除备份挖矿记录!!!!!!");
		try {
			miningRecordsService.removeByTimeout();
		} catch (Exception e) {
			LOGGER.error("===============================>删除备份挖矿记录失败!!!!!!", e);
		}

	}

	/**
	 * 获取用户截至到当天的ckt数量,每天23：30点执行
	 */
	@Scheduled(cron = "0 30 23 * * ?")
	public void getUserEthValue() {
		LOGGER.info("===============================>开始获取用户截至到当天的CKT数量!!!!!!");
		try {
			//List<SysUser> users = sysUserService.getAll();
			List<CktUser> cktUsers = cktUserService.getAll();
			List<CktRecord> cktRecordList = new ArrayList<CktRecord>();
			Map<String, String> consumeCktMap = cktRecordService.getPaymentRecord();
			Map<String, String> transCktMap = cktRecordService.getTransRecord();
			Map<String, String> exchangeCktMap = cktRecordService.getExchangeRecord();

			for (CktUser cktUser : cktUsers) {
				if (!StringUtils.isEmpty(cktUser.getCktId())) {
					Map<String, String> paraMap = new HashMap<String, String>();
					paraMap.put("addr", cktUser.getCktId());
					Map<String, String> head = new HashMap<String, String>();
					head.put("content-type", "Content-Type:application/json;charset=UTF-8");
					head.put("channel", "APP");
					head.put("rt", cktUser.getPhone().substring(5, cktUser.getPhone().length()));
					String para = JSONObject.fromObject(paraMap).toString();
					String responseBody = HttpUtils.postData("http://47.106.35.54/ckt/wallet/balance", para, head);
					JSONObject object = JSONObject.fromObject(responseBody);
					CktRecord record = new CktRecord();
					if (object.get("code").equals("0")) {
						JSONObject data = JSONObject.fromObject(object.get("data"));
						record.setCurrentCkt(data.get("balance") + "");
					} else {
						record.setCurrentCkt("0");
						record.setRemark(object.get("msg") + "");
					}
					if (!StringUtils.isEmpty(consumeCktMap.get(cktUser.getId()))) {
						record.setConsumeCkt(consumeCktMap.get(cktUser.getId()));
					} else {
						record.setConsumeCkt("0");
					}
					if (!StringUtils.isEmpty(transCktMap.get(cktUser.getId()))) {
						record.setTransCkt(transCktMap.get(cktUser.getId()));
					} else {
						record.setTransCkt("0");
					}
					if (!StringUtils.isEmpty(exchangeCktMap.get(cktUser.getId()))) {
						record.setExchangeCkt(exchangeCktMap.get(cktUser.getId()));
					} else {
						record.setExchangeCkt("0");
					}
					record.setUserId(cktUser.getId());
					record.setCktId(cktUser.getCktId());
					cktRecordList.add(record);
				}
			}
			cktRecordService.insertBatch(cktRecordList);
		} catch (Exception e) {
			LOGGER.error("===============================>获取用户截至到当天的CKT数量失败!!!!!!", e);
		}

	}

	public static void main(String[] args) {

		String url = "http://47.106.35.54/ckt/transact/query";
		Map<String, String> head = new HashMap<String, String>();
		Map<String, String> paraMap = new HashMap<String, String>();

		// 0xabbb8811f1e8d3611b21ad16593ad9ed4bee457c1e508806522431eb9edd2ff1
		paraMap.put("hash", "0x90a0bc0dac47c3bb49fd01df4ec09953759b664e19e41fc611aa73121d39dd79");
		head.put("content-type", "Content-Type:application/json;charset=UTF-8");
		head.put("channel", "APP");
		head.put("rt", "1234567890");
		// String info = HttpUtils.postHttp(url, paraMap, head);
		JSONObject jsonObject = JSONObject.fromObject(paraMap);
		String info = HttpUtils.postData(url, jsonObject.toString(), head);
		System.out.println(info);
		System.out.println(paraMap.toString());
		System.out.println(jsonObject.toString());

		// String
		// re
		// questStr="{\"requestEntity\":{\"paidMethod\":\"DT\",\"deliveryCustomerCode\":\"40001555\",\"receiveOrgCode\":\"W011302020515\",\"prePayAmount\":4568},\"type\":\"synchTradSettlement\"}";
		// RequestEntity entity = new
		// StringRequestEntity(requestStr,"application/json","UTF-8");
	}

}
